import { useEffect, useRef, useState } from "react"
export const isFalsy = (value: unknown) => value === 0 ? false : !value
export const isVoid = (value: unknown) => value === undefined || value === null || value === ""
export const clearObject = (object: { [key: string]: unknown }) => {
  const result = { ...object }
  Object.keys(result).forEach(key => {
    const value = result[key]
    if (isVoid(value)) {
      delete result[key]
    }
  })
  return result
}
export const useMount = (calback: () => void) => {
  useEffect(() => {
    calback()
    //TODO 依赖项里加上callback会造成无限循环，这个和usecallback以及userMemo有关系
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
}
export const useDebounce = <V>(value: V, delay?: number): V => {
  const [debouceValue, setDebounceValue] = useState(value)
  useEffect(() => {
    //每次value变化后设置定时器
    const timeOut = setTimeout(() => setDebounceValue(value), delay)
    return () => clearTimeout(timeOut)
  }, [value, delay])
  return debouceValue
}
export const useDocumentTitle = (titile: string, keepOnUnmount: boolean = true) => {
  let oldTitle = useRef(document.title).current
  useEffect(() => {
    document.title = titile
  }, [titile])
  useEffect(() => {
    return () => {
      if (!keepOnUnmount) {
        document.title = oldTitle
      }
    }
  }, [keepOnUnmount, oldTitle])
}
export const resetRoute = () => window.location.href = window.location.origin
export const useMountedRef = () => {
  const mountedRef = useRef(false)
  useEffect(() => {
    mountedRef.current = true
    return () => {
      mountedRef.current = false
    }
  })
  return mountedRef
}
